#include "FramesControl.h"


FramesControl::FramesControl (double fr, GLFWwindow* w) :
time (0), oldTime (0), dTime (0),
frameRate (fr), frameCount (0), window (w),
width (0), height (0), isActive (true),
timeCount (0), fpsCSV ("")
{
}
bool FramesControl::update (const int &w, const int &h)
{
   width = w;
   height = h;
   if (isActive == true) {
      time = glfwGetTime ();
      dTime = time - oldTime;
      if (dTime >= 1.0 / frameRate) {	//1.0 second
         frameCount++;
         oldTime = time;
         timeCount += 1.0;
         setWindowTitle ();
         return true;
      }
      frameCount = 0;
      return false;
   }
   else {
      time = glfwGetTime ();
      dTime = time - oldTime;
      if (dTime >= 1.0) {
         timeCount += 1.0f;
         setWindowTitle ();
         frameCount = 0;
         oldTime = time;
      }
      frameCount++;
      return true;
   }
}
void FramesControl::setWindowTitle (void)
{
   int frameTmp = frameCount*(int)frameRate;
   if (frameCount != 0) {
      char TempString[512];

      if (isActive == true) {
         sprintf (TempString, "Trabalho 3: %d Frames Per Second @ %d x %d\0", frameTmp, width, height);
         fpsCSV += std::to_string (frameTmp) + ";";
      }
      else {
         sprintf (TempString, "Trabalho 3: %d Frames Per Second @ %d x %d\0", frameCount, width, height);
         fpsCSV += std::to_string ((int)frameCount) + ";";
      }
      glfwSetWindowTitle (window, TempString);
      if (timeCount == 60.0) {
         writeFpsCSV ();
      }
   }

}
void FramesControl::writeFpsCSV ()
{
   std::ofstream fileOuput;
   fileOuput.open ("fpsOutput.csv");
   fileOuput << fpsCSV;
   fileOuput.close ();
}
void FramesControl::setActive (const bool &state)
{
   isActive = state;
}
void FramesControl::setFrameRate (const double &fr)
{
   frameRate = fr;
}
const double &FramesControl::getFrameRate (void)
{
   return frameRate;
}
FramesControl::~FramesControl ()
{
}
